import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { asyncRoutes } from './router'
NProgress.configure({ showSpinner: false })

const list = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  const token = store.state.user.token
  // token || list.includes(to.path) ? next() : next('/login')

  if (token) {
    if (to.path === '/login') {
      NProgress.done()
      document.title = to.meta.title
      next('/')
    } else {
      if (!store.state.user.userItem.userId) {
        const res = await store.dispatch('user/getUser')

        const filterAsyncRoutes = asyncRoutes.filter(item => {
          return res.roles.menus.includes(item.children[0].name)
        })
        // 404 page must be placed at the end !!!
        filterAsyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
        store.commit('menu/getMenus', filterAsyncRoutes)
        router.addRoutes(filterAsyncRoutes)
        next(to)
      } else {
        next()
      }
    }
  } else {
    // 没有token，只能访问白名单
    if (list.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

// router.beforeEach((to, from, next) => {
//   document.title = to.meta.title
// })

router.afterEach(() => {
  NProgress.done()
})

